/**
 * 销售出库管理初始化
 */
var GoodsSale = {
    id: "GoodsSaleTable",	//表格id
    seItem: null,		//选中的条目
    goodsSaleData:{},
    table: null,
    layerIndex: -1
};

/**
 * 初始化销售出库的 表格
 */
GoodsSale.initSalesTableColumn = function () {
    return [
        {field: 'selectItem', radio: true},
        {title: '商品ID', field: 'goodsId', visible: false, align: 'center', valign: 'middle'},
        {title: '销售数量', field: 'goodsNum', visible: true, align: 'center', valign: 'middle'},
        {title: '商品编码', field: 'goodsCode', visible: true, align: 'center', valign: 'middle'},
        {title: '商品型号', field: 'goodsModel', visible: true, align: 'center', valign: 'middle'},
        {title: '商品名称', field: 'goodsName', visible: true, align: 'center', valign: 'middle'},
        {title: '商品单位', field: 'goodsUnit', visible: true, align: 'center', valign: 'middle'},
        {title: '出售单价', field: 'goodsPrice', visible: true, align: 'center', valign: 'middle'},
        {title: '出售总价', field: 'totalPrice', visible: true, align: 'center', valign: 'middle'},
        {title: '订单ID', field: 'goodsSaleId', visible: false, align: 'center', valign: 'middle'},
        {title: '创建者', field: 'createBy', visible: false, align: 'center', valign: 'middle'},
        {title: '创建时间', field: 'createDate', visible: false, align: 'center', valign: 'middle'},
        {title: '更新者', field: 'updateBy', visible: false, align: 'center', valign: 'middle'},
        {title: '更新时间', field: 'updateDate', visible: false, align: 'center', valign: 'middle'},
        {title: '备注信息', field: 'remarks', visible: false, align: 'center', valign: 'middle'},
        {title: '删除标记（0：正常；1：删除）', field: 'delFlag', visible: false, align: 'center', valign: 'middle'}
    ];
};

/**
 * 清除数据
 */
GoodsSale.clearData = function () {
    this.goodsSaleData = {};
}
/**
 * 清除dom显示数据
 */
GoodsSale.clearDom = function () {
    this
        .setDomVal('id')
        .setDomVal('amountPaid')
        .setDomVal('amountPayable')
        .setDomVal('saleOrderNumber')
        .setDomVal('payState')
        .setDomVal('createBy')
        .setDomVal('createDate')
        .setDomVal('updateBy')
        .setDomVal('updateDate')
        .setDomVal('remarks')
        .setDomVal('delFlag')
        .setDomVal('customerId');
}

/**
 * 收集数据
 */
GoodsSale.collectData = function () {
    this
        .set('id')
        .set('amountPaid')
        .set('amountPayable')
        .set('saleOrderNumber')
        .set('customerId')
        .set('payState')
        .set('createBy')
        .set('createDate')
        .set('updateBy')
        .set('updateDate')
        .set('remarks')
        .set('delFlag');
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
GoodsSale.set = function (key, val) {
    this.goodsSaleData[key] = (typeof val === "undefined") ? $("#" + key).val() : val;
    return this;
}

/**
 * 设置dom中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
GoodsSale.setDomVal = function (key, val) {
    (typeof val === "undefined") ? $("#" + key).val('') : $("#" + key).val(val);
    return this;
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
GoodsSale.get = function (key) {
    return $("#" + key).val();
}


/**
 * 检查是否选中
 */
GoodsSale.check = function () {
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if(selected.length === 0){
        Feng.info("请先选中表格中的某一记录！");
        return false;
    }else{
        GoodsSale.seItem = selected[0];
        return true;
    }
};

/**
 * 点击添加销售出库
 */
GoodsSale.openAddGoodsSale = function () {
    var index = layer.open({
        type: 2,
        title: '添加销售出库',
        area: ['800px', '420px'], //宽高
        fix: false, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/goodsSale/goodsSale_add'
    });
    this.layerIndex = index;
};

/**
 * 删除销售出库
 */
GoodsSale.delete = function () {
    if (this.check()) {
        var selected = this.table.btInstance.bootstrapTable('getSelections');
        console.log(selected[0].goodsId);
        this.table.btInstance.bootstrapTable('removeByUniqueId',selected[0].goodsId);
    }
};


/**
 * 保存前检查数据
 */
GoodsSale.checkData = function () {
    var data = this.table.btInstance.bootstrapTable('getData', true);

    if ('' === data || typeof data === 'undefined' || data.length === 0) {
        Feng.info('请先添加商品!');
        return false;
    }

    var customer = $("#customerId option:selected").val();
    if ('' === customer || typeof customer === 'undefined') {
        Feng.info("请选择客户!");
        return false;
    }

    var amountPaid = $("#amountPaid").val();
    if ('' === amountPaid || typeof amountPaid === 'undefined') {
        Feng.info('请输入实付金额!');
        return false;
    }

    var createDate = $("#createDate").val();
    if('' === createDate || typeof createDate === 'undefined'){
        Feng.info("请选择销售日期!");
        return false;
    }

    var state = $("#payState option:selected").val();
    if ('' === state || typeof state === 'undefined') {
        Feng.info("请选择是否支付!");
        return false;
    }

    var saleOrderNumber = $("#saleOrderNumber").text();
    if ('' === saleOrderNumber || typeof saleOrderNumber === 'undefined') {
        Feng.info("订单号为空，请刷新页面重新提交!");
        return false;
    }

    return true;
}

/**
 * 保存销售订单
 */
GoodsSale.save = function(){
    if (this.checkData()) {
        //清除数据
        this.clearData();
        //获取form数据
        this.collectData();
        var ajax = new $ax(Feng.ctxPath + "/goodsSale/add", function (data) {
            Feng.success(data.message);
            //清除表单
            GoodsSale.clearData();
            //清除dom数据显示
            GoodsSale.clearDom();
            //清除表格数据
            GoodsSale.table.btInstance.bootstrapTable('removeAll');
            //输出
            console.log('新单号：', data.result);
            //重新赋值单号
            $("#saleOrderNumber").text(data.result);
        }, function (data) {
            Feng.error("获取供应商失败!" + data.responseJOSN.message + "!");
        });
        //获取单据号码
        this.goodsSaleData['saleOrderNumber'] = $('#saleOrderNumber').text();
        //获取添加的表格数据
        this.goodsSaleData['saleGoodsList'] = this.table.btInstance.bootstrapTable('getData', true);
        //请求数据
        var requestData = JSON.stringify(this.goodsSaleData);
        console.log("请求数据->", requestData);
        //设置为请求数据为json类型
        ajax.setContentType('application/json');
        ajax.setData(requestData);
        ajax.start();
    }
}

/**
 * 选中商品后计算出价格并赋值
 */
GoodsSale.calculateTotalPrice = function (cTotalPrice) {
    var cAmountPaid = $("#amountPaid").val();
    if (cAmountPaid === '') {
        $("#amountPaid").val(cTotalPrice);
    } else {
        var amountPaid = parseFloat(cAmountPaid);
        //累加价格
        $("#amountPaid").val(cTotalPrice + amountPaid);
    }
}

/**
 * 查询供应商
 */
GoodsSale.selectSupplier = function () {
    //查找下游客户下拉框
    var ajax = new $ax(Feng.ctxPath + "/managerCustomer/list", function (data) {
        $.each(data, function (index, supplier) {
            $("#customerId").empty();
            var customerId = supplier['id'];
            var customerName = supplier['customerName'];
            $("#customerId").html("<option value='" + customerId + "'>" + customerName + "</option>");
        })
    }, function (data) {
        Feng.error("获取供应商失败!" + data.responseJOSN.message + "!");
    });
    ajax.start();
}

/**
 * 是否支付下拉框
 */
GoodsSale.isPaySelect = function () {
    $("#payState").html("<option value='1'>已支付</option>" +
        "<option value='0'>未支付</option>")
}



$(function () {
    var defaultColunms = GoodsSale.initSalesTableColumn();
    var table = new BSTable(GoodsSale.id, "", defaultColunms);
    table.setShowColumns(false);
    table.setShowRefresh(false);
    table.setUniqueId("goodsId");
    table.setPaginationType("client");
    GoodsSale.table = table.init();
    //初始化事件
    GoodsSale.selectSupplier();
    GoodsSale.isPaySelect();
});
